package volkov.ja;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import volkov.ja.pages.TestBase;
import volkov.ja.util.MyProjectException;
import volkov.ja.util.TestLogger;

public class MovieSearchTest1 extends TestBase {
	private static TestLogger LOG;

	@BeforeClass
	public void prepareTest() {
		LOG = new TestLogger(MovieSearchTest1.class, getSessionId());
		LOG.info("Prepare environment: loading movies to the database");
		db.prepareFixture("movies");
		loginTestApplication();
	}

	@Test
	public void testMovieSearch1() throws Exception {
		String titleFull = "The Rabbit and the Treasures Trunk";
		String titlePart = "rabbit and";
		LOG.info("Go to the movies list");
		driver.get(baseUrl + "#!/sort/name%20asc/");
		driver.findElement(By.id("q")).clear();
		// By.id("results") doesn't work here, the wrapping element itself is
		// not updated by jQuery
		By byResults = By.cssSelector(".movie_box");
		// save old element to check its state later
		WebElement contentOld = driver.findElement(byResults);
		LOG.info("Start search of \"" + titlePart + "\"");
		driver.findElement(By.id("q")).sendKeys(titlePart + Keys.RETURN);
		getUpdatedElement(byResults, contentOld,
				"Result list wasn't updated after the search");
		// check results
		LOG.info("Check if the movie \"" + titleFull
				+ "\" is in the results list");
		List<WebElement> found = driver
				.findElements(By
						.xpath("//div[contains(@class, 'movie_box')]//div[@class='title']"));
		boolean oky = false;
		for (WebElement we : found) {
			if (we.getText().equals(titleFull)) {
				oky = true;
			}
		}
		if (!oky) {
			throw new MyProjectException("The expected movie \"" + titleFull
					+ "\" was not found in the results list");
		}
	}

}
